from datetime import datetime
from typing import TYPE_CHECKING, List

from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String, Table
from sqlalchemy.orm import relationship

from app.db.base_class import Base

if TYPE_CHECKING:
    from .contacts import Contact  # noqa: F401
    from .messages import Message  # noqa: F401


# 会话与联系人的多对多关系
session_contact = Table(
    "session_contact",
    Base.metadata,
    Column("session_id", Integer, ForeignKey("session.id"), primary_key=True),
    Column("contact_id", Integer, ForeignKey("contact.id"), primary_key=True),
)


class SessionType:
    INDIVIDUAL = "individual"
    GROUP = "group"


class Session(Base):
    """会话表"""
    id = Column(Integer, primary_key=True, index=True)
    session_type = Column(
        String(20), 
        default=SessionType.INDIVIDUAL, 
        comment="会话类型(个人/群组)"
    )
    name = Column(String(100), nullable=True, comment="会话名称")
    created_at = Column(DateTime, default=datetime.utcnow, comment="创建时间")
    last_active = Column(
        DateTime, 
        default=datetime.utcnow,
        onupdate=datetime.utcnow,
        comment="最后活跃时间"
    )
    
    # 关系
    contacts = relationship("Contact", back_populates="sessions", secondary=session_contact)
    messages = relationship("Message", back_populates="session", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<Session {self.name or self.id}>"